package com.zifeng.rocketmq;

import com.alibaba.fastjson.JSON;
import com.zifeng.pojo.Order;
import com.zifeng.pojo.ShipDto;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class OrderRocketMQProducer {

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    public void sendTransactionMessage(String topic, Order order) {

        Message<String> message = MessageBuilder.withPayload(JSON.toJSONString(order))
                .setHeader(RocketMQHeaders.TRANSACTION_ID, order.getId())
                // 设置一个业务的key,以便事务回查时使用
                .setHeader(RocketMQHeaders.KEYS, order.getId())
                .build();
        TransactionSendResult transactionSendResult =
                rocketMQTemplate.sendMessageInTransaction(topic, message, null);
        if (transactionSendResult.getSendStatus() == SendStatus.SEND_OK) {
            log.info("发送事务消息成功!消息ID为:{}", transactionSendResult.getMsgId());
        }
        log.info("消息发送状态：{}", transactionSendResult.getSendStatus());
    }
}
